//
//  YNSResultVC.m
//  HNBaseProject
//
//  Created by TR on 2024/7/23.
//

#import "YNSResultVC.h"
#import "YNSSaveView.h"
#import <UIKit/UIKit.h>
#import "YNSStartViewController.h"
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "KNPhotoBrowser.h"
#import <AFHTTPSessionManager.h>
@interface YNSResultVC ()<MxNavigationViewDelegate>

@property (nonatomic, strong) MxPublicNav *nav;
@property(nonatomic,strong)UIImageView*resultImg;
@property(nonatomic,strong)UIButton*saveBtn;
@property(nonatomic,strong)UIButton*againBtn;
@property(nonatomic,strong)UIButton*backBtn;

@property(nonatomic,strong)YNSSaveView*saveView;

@end

@implementation YNSResultVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
}
-(void)setUI{
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = NSLocalizedString(@"详情",nil);
    self.nav.delegate = self;
    self.nav.line.hidden = NO;
    self.nav.backButton.hidden = YES;
    self.nav.rightBtn.hidden = NO;
    [self.nav.rightBtn setImage:[UIImage imageNamed:@"home_back"] forState:UIControlStateNormal];
    [self.view addSubview:self.nav];
    
    self.resultImg = [[UIImageView alloc]init];
    self.resultImg.userInteractionEnabled = YES;
    [self.resultImg sd_setImageWithURL:[NSURL URLWithString:self.cover_image_url]];
    [self.view addSubview:self.resultImg];
    [self.resultImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nav.mas_bottom).offset(15);
        make.left.offset(23);
        make.right.offset(-23);
        make.height.offset(kRealValue(308));
    }];
    MJWeakSelf
    [self.resultImg addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapShowVideo];
    }]];
    
    
    self.saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.saveBtn setTitle:NSLocalizedString(@"保存视频",nil) forState:UIControlStateNormal];
    [self.saveBtn setTitleColor:[UIColor colorWithHexString:@"#1D8EFF"] forState:UIControlStateNormal];
    self.saveBtn.backgroundColor = [UIColor whiteColor];
    self.saveBtn.layer.masksToBounds = YES;
    self.saveBtn.layer.cornerRadius = 19;
    self.saveBtn.layer.borderColor = [UIColor colorWithHexString:@"#1D8EFF"].CGColor;
    self.saveBtn.borderWidth = 1;
    [self.saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.saveBtn];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.resultImg.mas_bottom).offset(32);
        make.left.offset(23);
        make.height.offset(38);
        make.width.offset((kScreenW-55)/2);
    }];
    
    self.againBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.againBtn setTitle:NSLocalizedString(@"再来一张",nil) forState:UIControlStateNormal];
    [self.againBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.againBtn.layer.masksToBounds = YES;
    self.againBtn.layer.cornerRadius = 21;
    [self.againBtn addTarget:self action:@selector(againClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.againBtn];
    [self.againBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.resultImg.mas_bottom).offset(32);
        make.width.offset((kScreenW-55)/2);
        make.right.offset(-23);
        make.height.offset(42);
    }];
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0, 0, (kScreenW-55)/2, 42);
    gl.startPoint = CGPointMake(1, 0.45);
    gl.endPoint = CGPointMake(0, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithHexString:@"#1D8EFF"].CGColor, (__bridge id)[UIColor colorWithHexString:@"#3BD5C5"].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    [self.againBtn.layer addSublayer:gl];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setTitle:NSLocalizedString(@"返回首页",nil) forState:UIControlStateNormal];
    [self.backBtn setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
    self.backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.saveBtn.mas_bottom).offset(29);
        make.centerX.equalTo(self.view.mas_centerX).offset(0);
        make.width.offset(160);
        make.height.offset(20);
    }];
//    self.backBtn.bounds = CGRectMake(0, 0, 160, 20);
//    [self.backBtn dc_borderForColor:[UIColor colorWithHexString:@"#999999"] borderWidth:1 borderType:UIBorderSideTypeBottom];
}

- (void)tapShowVideo {
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    NSMutableArray *data = [[NSMutableArray alloc] init];

    KNPhotoItems *items = [[KNPhotoItems alloc] init];
    items.url = SAFEPARAMETER(self.video_url);
    items.isVideo = YES;
    [data addObject:items];

    photoBrowser.itemsArr = data;
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedPageControl = false;
    photoBrowser.isNeedLongPress = false;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;

    [photoBrowser present];
}
#pragma mark----懒加载------
- (YNSSaveView*)saveView {
    if (!_saveView)
    {
        _saveView = [[YNSSaveView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    }
    return _saveView;
}
#pragma mark ---MxNavigationViewDelegate-----
- (void)rightTap {
    if (self.fromList) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        YNSStartViewController *vc = [[YNSStartViewController alloc]init];
        [self.navigationController popToViewController:vc animated:YES];
    }

}
- (void)leftTap {
    
}
#pragma mark----返回首页-----
-(void)backClick {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark------保存视频------
- (void)saveClick {
    //统计
    [[AppsFlyerLib shared]  logEvent: AFEventContentView withValues: @{
        AFEventParamContentId: @"2",
        AFEventParamContentType:@"保存视频"
    }];
    
    [self playerDownload:self.video_url];
}
#pragma mark------再来一次-----
-(void)againClick {
    if (self.fromList) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
//        YNSStartViewController *vc = [[YNSStartViewController alloc]init];
//        [self.navigationController popToViewController:vc animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }

}

#pragma mark----保存视屏到本地------

- (void)playerDownload:(NSString *)url{
    
    WEAKSELF;
       [SVProgressHUD show];
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    
        NSString *documentsDirectory = [paths objectAtIndex:0];
    
        NSURL *urlNew = [NSURL URLWithString:url];
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    for(int count = 0; count < 5; count ++) {
        
                if([url containsString:@"/"]) {
            
                        NSRange rang2 = [url rangeOfString:@"/"];
            
                        url = url ? [url substringFromIndex:rang2.location + 1] :nil;
            
                    }
        
            }
    
        //实际上获得的是：UTC时间，协调世界时，亚州的时间与UTC的时差均为+8
    
        NSDate * nowdate = [NSDate date];
    
        //zone为当前时区信息  在我的程序中打印的是@"Asia/Shanghai"
    
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
        //28800 //所在地区时间与协调世界时差距
    
    NSInteger interval = [zone secondsFromGMTForDate:nowdate];
    
        NSDate *localeDate = [nowdate dateByAddingTimeInterval: interval];
    
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    
        [formatter setDateFormat:@"yyyyMMddhhmmss"];
    
        NSString * dateStr = [formatter stringFromDate:localeDate];
    
        NSString  *fullPath = [NSString stringWithFormat:@"%@/%@%@", documentsDirectory, dateStr,url];
    
        NSURLRequest *request = [NSURLRequest requestWithURL:urlNew];
    
    NSURLSessionDownloadTask *task =
    
        [manager downloadTaskWithRequest:request
         
                                     progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
                                        return[NSURL fileURLWithPath:fullPath];
        
                                    }
         
                            completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
                             [SVProgressHUD dismiss];
                               [weakSelf saveVideo:fullPath];
        
                           }];
    
        [task resume];
    
}

-(void)saveVideo:(NSString*)videoPath {
    if(videoPath){
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath)) {
            UISaveVideoAtPathToSavedPhotosAlbum(videoPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
    }
}
- (void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (error)
    {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"保存失败", nil)];
    }
    else{
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"保存成功", nil)];
    }
}
@end
